import React from 'react';
import styles from './style.less';
import startRealTime from '../../component/realTime';
import giftsInfo from '../../info/giftsInfo';
import headImg from '../../static/images/head.svg';
import heartImg from '../../static/images/heart.svg';
import RandomNum from './randomNum';
import moment from 'moment';
import { getCurMoney } from './request';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import manInfo from './info'
const LUCK_MODE = false;
const SHOW_MODE = true;

class Show extends React.Component {
  constructor( props ) {
    super( props );
    this.state = {
      money: 0,
      // mode: SHOW_MODE,
      // moments:[]
      luckyIds: [],
      // 当前抽中的幸运狗
      curMan: {},
      // 金主
      moneyMan: [],
      //
      heartIn: false,
      mode: SHOW_MODE,
      moments: [
        {
        _id: '0',
        headimgurl: 'http://wx.qlogo.cn/mmopen/vi_32/x8cEYUlUuCM6PLYsHRic5WnUqy0jyNk3vgnbFDt0GEnaiaibvhq5XzbclrHbrOqCbLJGYGY1u01W2eiaB2YYkcTkCA/132',
        nickname: '朝朝',
        giftsArr: [ 1, 1, 1, 1, 1, 1 ],
        content: '花旦传媒越办越棒0!!',
        anonymous: false,
        time: new moment( new Date() ).format( 'MM-DD  HH:mm' )
      },
        {
        _id: '1',
        headimgurl: 'http://wx.qlogo.cn/mmopen/vi_32/x8cEYUlUuCM6PLYsHRic5WnUqy0jyNk3vgnbFDt0GEnaiaibvhq5XzbclrHbrOqCbLJGYGY1u01W2eiaB2YYkcTkCA/132',
        nickname: '朝朝',
        giftsArr: [ 1, 1, 1, 1, 1, 1 ],
        content: '花旦传媒越办越棒1!!',
        anonymous: false,
        time: new moment( new Date() ).format( 'MM-DD  HH:mm' )
      }, {
        _id: '2',
        headimgurl: 'http://wx.qlogo.cn/mmopen/vi_32/x8cEYUlUuCM6PLYsHRic5WnUqy0jyNk3vgnbFDt0GEnaiaibvhq5XzbclrHbrOqCbLJGYGY1u01W2eiaB2YYkcTkCA/132',
        nickname: '朝朝',
        giftsArr: [ 1, 1, 1, 1, 1, 1 ],
        content: '花旦传媒越办越棒2!!',
        anonymous: false,
        time: new moment( new Date() ).format( 'MM-DD  HH:mm' )
      } ]
    };
  }

  componentDidMount() {
    startRealTime( [
      {
        fn: this.getTheNewComment.bind( this ),
        event: 'newMoment'
      }, {
        fn: this.getTheNewMoney.bind( this ),
        event: 'money'
      }
    ] );



    // setTimeout(() => {
    //   let t = this.state.moments.slice();
    //   t.pop();
    //   t.unshift({
    //     _id: '3',
    //     headimgurl: 'http://wx.qlogo.cn/mmopen/vi_32/x8cEYUlUuCM6PLYsHRic5WnUqy0jyNk3vgnbFDt0GEnaiaibvhq5XzbclrHbrOqCbLJGYGY1u01W2eiaB2YYkcTkCA/132',
    //     nickname: '朝朝',
    //     giftsArr: [ 1, 1, 1, 1, 1, 1 ],
    //     content: '花旦传媒越办越棒!!',
    //     anonymous: false,
    //     time: new moment( new Date() ).format( 'MM-DD  HH:MM' )
    //   });
    //   this.setState({
    //     moments: t
    //   });
    // }, 1000);


    getCurMoney()
      .then( ( { money } ) => {
        this.setState( {
          money
        } );
      } )
      .catch( err => console.error( err ) );


  }

  // 获取赏金池弹幕动态
  getTheNewComment( data ) {
    console.log( data, '来自上数据库的消息' );
    let haveMoney = false;


    data.giftsArr.forEach( el => {
      if( el > 0){
        haveMoney = true;
      }
    } );

    if( haveMoney ){
      let moneyMan = this.state.moneyMan.slice();
      moneyMan.push(data);
      let { heartIn } = this.state;
      if(!heartIn ) heartIn = true;
      this.setState({
        moneyMan,
        heartIn
      });
    }

    data.time = new moment().format( 'MM-DD  HH:mm' );
    this.setState( prev => {
      let temp = prev.moments.slice();
      temp.unshift( data );
      if ( temp.length > 3 ) {
        temp.pop();
      }

      return {
        moments: temp
      };
    } );
  };

  // 获取赏金池当前赏金
  getTheNewMoney( data ) {
    console.log( data, '新的赏金已经出现' );
    let { money } = data;
    if ( !money ) throw Error( '后台返回的赏金数目有问题' );

    this.setState( {
      money
    } );

  }

  changeMode(){
    this.setState({
      mode: !this.state.mode,
      curMan: {}
    });
  }

  // 抽取到幸运儿啦
  returnTheLuckDog(curMan){
    let ids = this.state.luckyIds.slice();
    if( ids.length > 1 ){
      ids = [];
    }
    ids.push( curMan.id );
    this.setState({
      luckyIds: ids
    });
  };

  begin(){
    let arr = [];

    for ( let key in manInfo ){
      if ( manInfo.hasOwnProperty(key ) ){
        arr.push( {
          name: key,
          id: manInfo[key]
        } );

      }
    }

    let man = arr[Math.floor(Math.random() * arr.length)];

    this.setState({
      curMan: man
    });


  }

  // 看看还有没有金主， 有金主的话再触发一次
  checkMoneyMan(){
     this.setState({
       heartIn: false
     }, () => {
       let { moneyMan, heartIn } = this.state;
       let newMan = moneyMan.slice();
       newMan.pop();

       if(newMan.length > 0){
         // 触发显示金主动画
         heartIn = true
       }

       this.setState({
         moneyMan: newMan,
         heartIn
       });
     });


  }

  renderGifts( giftsArr = [] ) {
    let gifts = giftsArr.map( ( e, i ) => ({ val: e, index: i }) )
      .filter( e => e.val !== 0 );
    if ( gifts.length === 0 ) {
      return null;
    }

    return (
      <div className={ styles.gifts }>
        送出：
        {
          gifts.map( ( el, index ) => {
            return (
              <span key={ index }>
                <img className={ styles.giftImg } src={ giftsInfo[ el.index ].img } alt="礼物"/>
                * { el.val }
                { index === gifts.length - 1 ? '。' : '、' }
              </span>
            );
          } )
        }
      </div>
    );
  }

  renderComments() {
    let { moments } = this.state;
    return (
      <TransitionGroup className={ styles.moments }>
        {
          moments.map( el => {
            let { anonymous, headimgurl } = el;
            let headImgUrl = headimgurl;
            if ( anonymous ) headImgUrl = headImg;
            return (
              <CSSTransition in={ true }
                             classNames="show-fade"
                             timeout={ 1000 }
                             exit={false}
                             key={ el._id }>
                <div key={ el._id } className={ styles.moment }>
                  { /********************* 头像区 **************************/ }
                  <div className={ styles.headWrap }>
                    <div className={ styles.headOut }>
                      <div className={ styles.headIn }>
                        <img src={ headImgUrl } alt=" 头像"/>
                      </div>
                    </div>
                  </div>

                  { /********************* 内容区 *************************/ }
                  <div className={ styles.content }>
                    { /********************* 姓名与时间 *************************/ }
                    <div className={ styles.cHead }>
                      <div className={ styles.name }>
                        { anonymous ? '匿名旦仔' : el.nickname }
                      </div>
                      <div className={ styles.time }>
                        { el.time }
                      </div>
                    </div>

                    { /********************* 礼物 *************************/ }
                    { this.renderGifts( el.giftsArr ) }

                    { /********************* 留言 *************************/ }
                    {
                      el.content &&
                      <div className={ styles.sayContent }>
                        { el.content }
                      </div>
                    }
                  </div>
                </div>
              </CSSTransition>
            );

          } )
        }
      </TransitionGroup>
    );

  };

  renderLuckyDogPicker() {
    let { luckyIds, curMan } = this.state;
    return (
      <div className={ styles.luckyDog }>
        <div className={ styles.luckyDogCom }>
          幸运id:&nbsp;&nbsp;
          {
            luckyIds.map( ( el, index ) => {
              let end = '、';
              if( index === luckyIds.length - 1  ) end = '。';
              return el + end;
            } )
          }
        </div>
        <div className={ styles.makeSomeLuck }>
          <RandomNum value={ curMan.id }
                     onFinish={ this.returnTheLuckDog.bind( this, curMan ) } />
          <div className={styles.beginButton}
               onClick={ this.begin.bind(this) }>开始抽奖</div>
        </div>
      </div>
    );
  };


  render() {
    let { money, mode, moneyMan, heartIn } = this.state;

    return (
      <div className={ styles.show }>
        <CSSTransition in={heartIn}
          classNames="show-heart"
                       timeout={ 5000}
                  onEntered={ this.checkMoneyMan.bind(this) }>
          <div className={ styles.heart}>
            <img src={heartImg} alt="财主"/>
            <div className={ styles.giftText}>
              感谢土豪&nbsp;"{moneyMan[0] && !moneyMan[0].anonymous ?
              moneyMan[0].nickname : '匿名朋友'}"&nbsp;送出礼物！！！
            </div>
          </div>
        </CSSTransition>
        <div className={ styles.money } onClick={ this.changeMode.bind(this) }>
          ¥ { parseInt(money) / 100 }
        </div>
        { mode === SHOW_MODE && this.renderComments() }
        { mode === LUCK_MODE && this.renderLuckyDogPicker() }
      </div>
    );
  }
}

export default Show;